package com.inhim.pjhim.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.inhim.pjhim.R;
import com.inhim.pjhim.activity.SearchNewActivity;
import com.inhim.pjhim.adapter.ReadingTwoAdapter;
import com.inhim.pjhim.app.MyApplication;
import com.inhim.pjhim.base.ClassicsHeader;
import com.inhim.pjhim.entity.BannerList;
import com.inhim.pjhim.entity.ReaderList;
import com.inhim.pjhim.entity.ReaderListenList;
import com.inhim.pjhim.entity.ReaderReadList;
import com.inhim.pjhim.entity.ReaderStyle;
import com.inhim.pjhim.entity.ReaderTypeList;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.utils.StatusBarUtils;
import com.inhim.pjhim.view.BToast;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Request;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * create an instance of this fragment.
 */
public class VideoFragment extends Fragment {
    private RecyclerView mRecyclerView;
    private ReadingTwoAdapter mAdapter;
    private BannerList bannerList;
    private Gson gson;
    //private ReaderStyle.ReaderStyleValue readerStyleValue;
    private List homeList;
    private List mLastList;
    private SmartRefreshLayout home_SwipeRefreshLayout;
    private int mPageNum = 1;
    private Boolean refresh = true;
    private ReaderStyle.List rederType;
    private String TAG = "VideoFragment";
    private LinearLayout rela_search;
    private Context mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_reading_two, container, false);
        Bundle bundle = getArguments();
        mContext=getActivity();
        //readerStyleValue = (ReaderStyle.ReaderStyleValue) bundle.getSerializable("result");
        gson = new Gson();
        initView(view);
        homeList = new ArrayList();
        initAdapter();
        getBannerList();
        return view;
    }

    private void initView(View view) {
        View statusBar = view.findViewById(R.id.statusBarView);
        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
        layoutParams.height = MyApplication.getStatusBarHeight();
        mRecyclerView = view.findViewById(R.id.recyclerview);
        home_SwipeRefreshLayout = view.findViewById(R.id.home_SwipeRefreshLayout);
        home_SwipeRefreshLayout.setOnRefreshListener(refreshlayout -> {
            mPageNum = 1;
            refresh = true;
            //请求数据
            getBannerList();
        });
        home_SwipeRefreshLayout.setOnLoadmoreListener(refreshlayout -> {
            //加载
            /*mPageNum++;
            refresh = false;
            getReaderList(2);*/
            home_SwipeRefreshLayout.finishLoadmore();      //加载完成
        });
        /**
         * 设置不同的头部、底部样式
         */
        home_SwipeRefreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        home_SwipeRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));
        rela_search=view.findViewById(R.id.rela_search);
        rela_search.setOnClickListener(v -> {
            Intent intent=new Intent(mContext, SearchNewActivity.class);
            startActivity(intent);
        });
    }

    private void initAdapter() {
        mAdapter = new ReadingTwoAdapter(homeList, getActivity(), TAG);
        mRecyclerView.setAdapter(mAdapter);
        /*mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));*/
        setLayoutManager();
    }

    private void setLayoutManager(){
        // 设置布局管理
        List dateList=mAdapter.getData();
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 6);
        // 设置布局管理一条数据占用几行，如果是头布局则头布局自己占用一行
        try{
            manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int postion) {
                    if (dateList.get(postion) instanceof ReaderList.List) {
                        return 3;
                    }else if (dateList.get(postion) instanceof ReaderListenList.List) {
                        return 2;
                    }else if (dateList.get(postion) instanceof ReaderReadList.List) {
                        return 6;
                    } else {
                        return 6;
                    }
                }
            });
            mRecyclerView.setLayoutManager(manager);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void getReaderTypeList() {
        /** {
         "readerStyleId": "string",
         "readerStyleValueId": "string",
         "readerTypeId": "string",
         "title": "string"
         }*/
        HashMap postMap = new HashMap();
        String url = Urls.getReaderTypeList(mPageNum, 8, "", 0);
        MyOkHttpClient.getInstance().asyncJsonPost(url, postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                getReaderList(2);
            }

            @Override
            public void onSuccess(Request request, String result) {
                try {
                    ReaderTypeList readerTypeList = gson.fromJson(result, ReaderTypeList.class);
                    if (readerTypeList.getCode() == 0 && readerTypeList.getPage().getList().size() > 0) {
                        homeList.add(readerTypeList);
                    } else if (readerTypeList.getCode() != 0) {
                        BToast.showText(readerTypeList.getMsg(), false);
                    }
                    mAdapter.notifyDataSetChanged();
                    getReaderList(2);
                } catch (Exception e) {
                    getReaderList(2);
                    e.printStackTrace();
                }
            }
        });
    }

    private void getReaderList(int tagId) {
        HashMap postMap = new HashMap();
        postMap.put("type",tagId);
        //1: 推荐 0：不推荐
        postMap.put("intRecommend",1);
        String url=Urls.getReaderList(mPageNum, 8,"desc");
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(url, postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                getReaderListenList(3);
            }

            @Override
            public void onSuccess(Request request, String result) {
                try {
                    Gson gson = new Gson();
                    ReaderList readerList = gson.fromJson(result, ReaderList.class);
                    if (readerList.getCode() == 0 && readerList.getPage().getList().size() > 0) {
                        if (refresh) {
                            homeList.add("猜你喜欢看");
                        }
                        homeList.addAll(readerList.getPage().getList());
                        mAdapter.notifyDataSetChanged();
                    } else if (readerList.getCode() != 0) {
                        BToast.showText(readerList.getMsg(), false);
                    }
                    getReaderListenList(3);
                } catch (Exception e) {
                    getReaderListenList(3);
                }
            }
        });
    }

    private void getReaderListenList(int tagId) {
        HashMap postMap = new HashMap();
        postMap.put("type", tagId);
        //1: 推荐 0：不推荐
        postMap.put("intRecommend",1);
        String url=Urls.getReaderList(mPageNum, 6,"desc");
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(url, postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                getReaderReadList(1);
            }

            @Override
            public void onSuccess(Request request, String result) {
                try {
                    Gson gson = new Gson();
                    ReaderListenList readerList = gson.fromJson(result, ReaderListenList.class);
                    if (readerList.getCode() == 0 && readerList.getPage().getList().size() > 0) {
                        if (refresh) {
                            homeList.add("大家都在听");
                        }
                        homeList.addAll(readerList.getPage().getList());
                    } else if (readerList.getCode() != 0) {
                        BToast.showText(readerList.getMsg(), false);
                    }
                    mAdapter.notifyDataSetChanged();
                    getReaderReadList(1);
                } catch (Exception e) {
                    e.printStackTrace();
                    getReaderReadList(1);
                }
            }
        });
    }

    private void getReaderReadList(int tagId) {
        HashMap postMap = new HashMap();
        postMap.put("type", tagId);
        //1: 推荐 0：不推荐
        postMap.put("intRecommend",1);
        String url=Urls.getReaderList(mPageNum, 3,"desc");
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(url, postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                home_SwipeRefreshLayout.finishRefresh();  //刷新完成
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onSuccess(Request request, String result) {
                try {
                    home_SwipeRefreshLayout.finishRefresh();  //刷新完成
                    Gson gson = new Gson();
                    ReaderReadList readerList = gson.fromJson(result, ReaderReadList.class);
                    if (readerList.getCode() == 0 && readerList.getPage().getList().size() > 0) {
                        if (refresh) {
                            homeList.add("最多阅读");
                        }
                        homeList.addAll(readerList.getPage().getList());
                    } else if (readerList.getCode() != 0) {
                        BToast.showText(readerList.getMsg(), false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if(mLastList==null||mLastList.size()!=homeList.size()){
                        mAdapter.notifyDataSetChanged();
                    }
                    mLastList=homeList;
                }
                if(mLastList==null||mLastList.size()!=homeList.size()){
                    mAdapter.notifyDataSetChanged();
                }
                mLastList=homeList;
            }
        });
    }

    private boolean mIsLoading;
    private void getBannerList() {
        MyOkHttpClient.getInstance().asyncGetNoToken(Urls.getBannerList(3), new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                getReaderTypeList();
            }

            @Override
            public void onSuccess(Request request, String result) {
                try {
                    bannerList = gson.fromJson(result, BannerList.class);
                    if (refresh) {
                        homeList.clear();
                    }
                    if (bannerList.getCode() == 0 && bannerList.getData().size() > 0) {
                        homeList.add(bannerList);
                    } else if (bannerList.getCode() != 0) {
                        BToast.showText(bannerList.getMsg(), false);
                    }
                    mAdapter.notifyDataSetChanged();
                    getReaderTypeList();
                } catch (Exception e) {
                    getReaderTypeList();
                    e.printStackTrace();
                }

            }
        });
    }
}